const EventProxy = require('eventproxy');
const models     = require('../models');
const Topic      = models.Topic;
const User       = require('./user');
const Reply      = require('./reply');
const tools      = require('../common/tools');
const at         = require('../common/at');
const _          = require('lodash');


// create new topic
exports.newAndSave = function (title, content, tab, author, callback) {
    let topic = new Topic();

    topic.title = title;
    topic.content = content;
    topic.tab_value = tab.value;
    topic.tab_key = tab.key;
    topic.author_id = author.authorId;
    topic.author_name = author.authorName;
    topic.avatar = author.avatar;

    topic.save(callback);
};

//获取文章
exports.getFullTopic = function (query, opt, callback) {
    Topic.find(query, opt, function (err, topics) {
        if (err) {
            return callback(err);
        }
        if (topics.length === 0) {
            return callback(null, []);
        }

        let proxy = new EventProxy();
        proxy.after('topic_ready', topics.length, function () {
            topics = _.compact(topics); // 删除不合规的 topic
            return callback(null, topics);
        });
        proxy.fail(callback);

        // topics.forEach(function (topic, i) {
        //     let ep = new EventProxy();
        //     ep.all('author', 'reply', function (author, reply) {
        //         // 保证顺序
        //         // 作者可能已被删除
        //         if (author) {
        //             topic.author = author;
        //             topic.reply = reply;
        //         } else {
        //             topics[i] = null;
        //         }
        //         proxy.emit('topic_ready');
        //     });
        // });
    });
};

/**
 * 根据关键词，获取主题列表
 * Callback:
 * - err, 数据库错误
 * - count, 主题列表
 * @param {String} query 搜索关键词
 * @param {Object} opt 搜索选项
 * @param {Function} callback 回调函数
 */
exports.getTopicsByQuery = function (query, opt, callback) {
    // query.deleted = false;
    Topic.find(query, {}, opt, function (err, topics) {
        if(err) {
            return callback(err);
        }
        if(topics.length === 0) {
            return callback([]);
        }

        return callback(topics);

        // let proxy = new EventProxy();
        // proxy.after('topic_ready', topics.length, function () {
        //     topics = _.compact(topics); //删除不合规的 topic
        //     return callback(null, topics);
        // });
        // proxy.fail(callback);
        //
        // topics.forEach(function (topic, i) {
        //     let ep = new EventProxy();
        //     ep.all('author', 'reply', function (author, reply) {
        //         // 保证顺序
        //         // 作者可能已被删除
        //         if(author) {
        //             topic.author = author;
        //             topic.reply = reply;
        //         } else {
        //             topic[i] = null;
        //         }
        //         proxy.emit('topic_ready');
        //     });
        //
        //     User.getUserById(topic.author_id, ep.done('author'));
        //     // 获取主题的最后回复
        //     // Reply.getReplyById(topic.last_reply, ep.done('reply'));
        // })
    })
};

//查看详情
exports.getTopicById = function (topicId, callback) {
    Topic.findOne({_id: topicId, deleted: false}, function (err, topic) {
        if(err) {
            return callback(err);
        }
        if(!topic) {
            return callback(null, []);
        }
        Reply.getRepliesByTopicId(topic._id, function (replies) {
            callback(topic, replies);
        });
    })
};

/**
 * 更新主题的最后回复信息
 * @param {String} topicId 主题ID
 * @param {String} replyId 回复ID
 * @param {Function} callback 回调函数
 */
exports.updateLastReply = function (topicId, replyId, callback) {
    Topic.findOne({_id: topicId}, function (err, topic) {
        if (err || !topic) {
            return callback(err);
        }
        topic.last_reply    = replyId;
        topic.last_reply_at = new Date();
        topic.reply_count += 1;
        topic.save();
        // topic.save(callback);
    });
};

/**
 * 将当前主题的回复计数减1，并且更新最后回复的用户，删除回复时用到
 * @param {String} id 主题ID
 * @param {Function} callback 回调函数
 */
exports.reduceCount = function (id, callback) {
    Topic.findOne({_id: id}, function (err, topic) {
        if(err) {
            return callback(err)
        }
        if(!topic) {
            // let response = new Response(0, '', '该主题不存在');
            return callback(new Error('该主题不存在'));
        }
        topic.reply_count -= 1;
        // topic.save();
        Reply.getLastReplyByTopId(id, function (err, reply) {
            // console.log('reply-----', reply);
            if(err) {
                return callback(err)
            }

            if(reply.length !== 0) {
                topic.last_reply = reply[0]._id;
                topic.last_reply_at = reply[0].update_at;
            } else {
                topic.last_reply = null;
                topic.last_reply_at = null;
            }

            topic.save();
        })
    })
};

//根据_id获取文章
// exports.getTopicById = function (tab, callback) {
//     let _tab = tab || '';
//
//     Topic.find({"tab": "share"}, callback);
//     // Topic.find({"tab": "share"}, function (err, list) {
//     //     // console.log(list);
//     //     callback(err, list);
//     // })
//     // if(_tab) {
//     //     Topic.find({}, function (err, list) {
//     //         console.log(list);
//     //         // res.send({code: 1, data: list});
//     //         return callback(list);
//     //     })
//     // }
// };
